﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data.SqlServerCe;
using System.Collections;

namespace EWS
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            tmrRefreshList.Enabled = true;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            // Liste abdunkeln, wenn noch nicht dunkel.
            tmrDisibleButton.Tag = "1";
            tmrRefreshList.Enabled = false;

            // DIALOG: Neuer Patient
            frmAddPatient frmAP = new frmAddPatient();
            frmAP.ShowDialog();
            
            //Liste wieder aufhellen
            patientList1.MakeDark(false);
            tmrRefreshList.Enabled = true;
            tmrDisibleButton.Tag = "0";
        }


        private void btnConfig_Click(object sender, EventArgs e)
        {
            tmrDisibleButton.Tag = "1";
            tmrRefreshList.Enabled = false;

            frmConfig frmCfg = new frmConfig();
            frmCfg.ShowDialog();

            //Liste wieder aufhellen
            patientList1.MakeDark(false);
            tmrRefreshList.Enabled = true;
            tmrDisibleButton.Tag = "0";
        }



        private void lblCaption_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            // TestForm will contain the per-pixel-alpha dib
            PerPxlAlphaBlend.MyAboutForm TestForm = new PerPxlAlphaBlend.MyAboutForm();
            TestForm.Width = 500;
            TestForm.Height = 370;
            //TestForm.Parent = this;
            TestForm.StartPosition = FormStartPosition.CenterScreen;
            //TestForm.Location =  new Point(this.Location.X + ((this.Width - 500) / 2),this.Location.Y + ((this.Height - 370) / 2));
            TestForm.Show();

            Bitmap btm = (Bitmap)Bitmap.FromFile("about_x64.dll");
            TestForm.SetBitmap(btm, 255);

            this.Enabled = true;
        }


        private void btnDelete_Click(object sender, EventArgs e)
        {
            //Liste abdunkeln
            tmrDisibleButton.Tag = "1";
            tmrRefreshList.Enabled = false;

            // Wichtig: Gegenfrage
            DialogResult result = MessageBox.Show("Sind Sie sicher das der Zustand dieses Patienten nicht mehr Überwacht werden soll?", "Patient ausblenden", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

            // Wenn Ja dann Patient ausblenden
            if (result == System.Windows.Forms.DialogResult.Yes)
            {
                PatientList.PLItem myData = (PatientList.PLItem)patientList1.myList[patientList1.getSelected()];
                DeletePatientDB(myData.Data.ID);

                RefreshList();
            }
            

            //Liste wieder aufhellen
            patientList1.MakeDark(false);
            tmrRefreshList.Enabled = true;
            tmrDisibleButton.Tag = "0";
        }





        void DeletePatientDB(uint id) {
            // Verbinndung aufbauen
            SqlCeConnection conn = new SqlCeConnection(Properties.Settings.Default.EWS_DatabaseConnectionString);
            conn.Open();

            // Commando aufbauen
            SqlCeCommand cmd = conn.CreateCommand();
            cmd.Connection = conn;

            cmd.CommandText = @"UPDATE Patient SET DeleteFlag=1 WHERE PaID=@id";
            cmd.Parameters.AddWithValue("@id", id);

            int result = cmd.ExecuteNonQuery();

            conn.Close();
        }

        private void frmMain_Layout(object sender, LayoutEventArgs e)
        {
            AutomaticLayouter();
        }

        private void patientList1_SampleEventActive(object sender, int iNo)
        {
            btnEdit.Visible = true;
            btnDelete.Visible = true;
            btnMeasureData.Visible = true;
        }

        private void patientList1_SampleEventDeActive(object sender)
        {
            btnEdit.Visible = false;
            btnDelete.Visible = false;
            btnMeasureData.Visible = false;
        }

        void ShowButton(PictureBox button)
        {
            if (tmrDisibleButton.Enabled==false) patientList1.MakeDark(true);
            tmrDisibleButton.Enabled = false;
            
            Bitmap b = new Bitmap(button.Width, button.Height);
            Graphics g = Graphics.FromImage(b);
            if (patientList1.picUC.BackgroundImage != null) g.DrawImage(patientList1.picUC.BackgroundImage, new Rectangle(0, 0, button.Width, button.Height), new Rectangle(0, button.Top - patientList1.Top, button.Width, button.Height), GraphicsUnit.Pixel);
            if (patientList1.picUC.Image != null) g.DrawImage(patientList1.picUC.Image, new Rectangle(0, 0, button.Width, button.Height), new Rectangle(0, button.Top - patientList1.Top, button.Width, button.Height), GraphicsUnit.Pixel);
            button.BackgroundImage = b;

            button.Visible = true;
        }

        void HideButton(PictureBox button)
        {
            button.Visible = false;
            if (tmrDisibleButton.Tag.ToString() == "0") tmrDisibleButton.Enabled = true;
        }

        private void btnAdd_MouseEnter(object sender, EventArgs e)
        {
            ShowButton(btnAdd_B);
        }

        private void btnAdd_MouseLeave(object sender, EventArgs e)
        {
            HideButton(btnAdd_B);   
        }

         private void btnEdit_MouseEnter(object sender, EventArgs e)
         {
             ShowButton(btnEdit_B);
         }

         private void btnEdit_MouseLeave(object sender, EventArgs e)
         {
             HideButton(btnEdit_B);  
         }

         private void btnDelete_MouseEnter(object sender, EventArgs e)
         {
             ShowButton(btnDelete_B);
         }

         private void btnDelete_MouseLeave(object sender, EventArgs e)
         {
             HideButton(btnDelete_B); 
         }

         private void btnConfig_MouseEnter(object sender, EventArgs e)
         {
             ShowButton(btnConfig_B);
         }

         private void btnConfig_MouseLeave(object sender, EventArgs e)
         {
             HideButton(btnConfig_B);
         }

         private void frmMain_Resize(object sender, EventArgs e)
         {
             AutomaticLayouter();
         }

         private void btnMeasureData_MouseEnter(object sender, EventArgs e)
         {
             ShowButton(btnMeasureData_B);
         }

         private void btnMeasureData_MouseLeave(object sender, EventArgs e)
         {
             HideButton(btnMeasureData_B);
         }


         private void AutomaticLayouter() {
             btnConfig.Top = this.Height - 200;
             btnConfig_B.Top = this.Height - (200 - 74);

             lblTemp.Width = Convert.ToInt32((patientList1.Width - 208) * 0.2);
             lblBlutdruck.Width = Convert.ToInt32((patientList1.Width - 208) * 0.2144);
             lblPuls.Width = Convert.ToInt32((patientList1.Width - 208) * 0.1712);
             lblSauerst.Width = Convert.ToInt32((patientList1.Width - 208) * 0.2144);
             lblAtemf.Width = Convert.ToInt32((patientList1.Width - 208) * 0.2);

             lblTemp.Left = 180;
             lblBlutdruck.Left = 180 + lblTemp.Width;
             lblPuls.Left = 180 + lblTemp.Width + lblBlutdruck.Width;
             lblSauerst.Left = 180 + lblTemp.Width + lblBlutdruck.Width + lblPuls.Width;
             lblAtemf.Left = 180 + lblTemp.Width + lblBlutdruck.Width + lblPuls.Width + lblSauerst.Width;
             optState.Left = patientList1.Width + patientList1.Left - (optState.Width + 10);
         }


         private void tmrDisibleButton_Tick(object sender, EventArgs e)
         {
             patientList1.MakeDark(false);
             tmrDisibleButton.Enabled = false;
         }

         void RefreshList()
         {

             //############################################################## Aktive Patienten abfragen
             // Verbinndung aufbauen
             SqlCeConnection conn = new SqlCeConnection(Properties.Settings.Default.EWS_DatabaseConnectionString);
             conn.Open();

             // Commando aufbauen
             SqlCeCommand cmd = conn.CreateCommand();
             cmd.CommandText = @"SELECT * FROM Patient WHERE DeleteFlag=0 ORDER BY Nachname";


             // Commando ausführen
             cmd.ExecuteScalar();
             SqlCeDataReader reader = cmd.ExecuteReader();

             // Liste reseten
             patientList1.myList.Clear();



             // In Liste einfügen
             while (reader.Read())
             {

                 //############################################################ Jetzt alle Datensätze holen
                 // Commando aufbauen
                 cmd = conn.CreateCommand();
                 cmd.CommandText = @"SELECT * FROM PatientData WHERE fkPaID=@fkpaid ORDER BY Timestamp DESC";
                 cmd.Parameters.AddWithValue("@fkpaid", reader.GetInt32(0));

                 // Commando ausführen
                 cmd.ExecuteScalar();
                 SqlCeDataReader reader2 = cmd.ExecuteReader();

                 if (reader2.Read() != false) {
                     PatientList.PLItem myItem = new PatientList.PLItem();
                     PatientList.Patient myPatient = new PatientList.Patient();
                     PatientList.PatientData myPatientData = new PatientList.PatientData();
                     myPatientData.ID = Convert.ToUInt32(reader2.GetInt32(0));
                     myPatientData.Atemfrequenz = Convert.ToUInt32(reader2.GetString(6));
                     myPatientData.Blutdruck = Convert.ToUInt32(reader2.GetString(3));
                     myPatientData.Puls = Convert.ToUInt32(reader2.GetString(4));
                     myPatientData.Sauerstoffsaettigung = Convert.ToUInt32(reader2.GetString(5));
                     myPatientData.Temperatur = float.Parse(reader2.GetString(2));
                     myPatient.aktuelleDaten = myPatientData;
                     myPatient.ID = Convert.ToUInt32(reader.GetInt32(0));
                     myPatient.name = reader.GetString(2);
                     myPatient.vorname = reader.GetString(1);
                     myItem.Data = myPatient;
                     patientList1.myList.Add(myItem);
                 }

                 
            
             }

             // Verbinndung schließen
             conn.Close();

             // Wenn nach Zustand sotieren ...
             if (optState.Checked == true)
             {
                 patientList1.myList.Sort(new CompareStatus());
             }

             patientList1.RedrawAll();
             //patientList1.RedrawShowArea();

             toolStripStatusLabelListCount.Text = patientList1.myList.Count.ToString() + " Patienten";
         }


        private void  AssignPatientDataToPatient() {
            
            // Verbinndung aufbauen
            SqlCeConnection conn = new SqlCeConnection(Properties.Settings.Default.EWS_DatabaseConnectionString);
            conn.Open();


            //############################################################## Aktive Patienten abfragen
            // Commando aufbauen
            SqlCeCommand cmd = conn.CreateCommand();
            cmd.CommandText = @"SELECT * FROM Patient WHERE DeleteFlag=0 ORDER BY NACHNAME" ;

            // Commando ausführen
            cmd.ExecuteScalar();
            SqlCeDataReader reader = cmd.ExecuteReader();

            //############################################################## Von allen Handynummer herausfinden

            while (reader.Read())
            {
                // Commando aufbauen
                SqlCeCommand cmd2 = conn.CreateCommand();
                cmd2.Connection = conn;
                cmd2.CommandText = @"SELECT * FROM PatientData WHERE fkPaID=@fkpaid ORDER BY Timestamp DESC";
                cmd2.Parameters.AddWithValue("@fkpaid", reader.GetInt32(0));

                // Commando ausführen
                cmd2.ExecuteScalar();
                SqlCeDataReader reader2 = cmd2.ExecuteReader();
                if (reader2.Read())
                {

                    //######################################################### Jetzt alle PatientData mit der Handynummer auf PatientID setzen

                    // Commando aufbauen
                    SqlCeCommand cmd3 = conn.CreateCommand();
                    cmd3.Connection = conn;

                    cmd3.CommandText = @"UPDATE PatientData SET fkPaID=@new_patient_id WHERE Handynummer=@hnr AND fkPaID=1";
                    cmd3.Parameters.AddWithValue("@new_patient_id", reader.GetInt32(0));
                    string hdr = reader2.GetString(1);
                    cmd3.Parameters.AddWithValue("@hnr", hdr);

                    int result = cmd3.ExecuteNonQuery();
                }

            }


            conn.Close();

                 
        }




         private void tmrRefreshList_Tick(object sender, EventArgs e)
         {
             AssignPatientDataToPatient();// weit den Patienen ihre Daten zu, welche auf fkPA auf 1 haben
             RefreshList();
             ShowWarnings();
         }

         void ShowWarnings()
         {
             ArrayList myPatienten = new ArrayList();

             for (int i=0 ; i< patientList1.myList.Count;i++) {
                 PatientList.PLItem myItem =(PatientList.PLItem) patientList1.myList[i];

                 if (myItem.Data.getStatus() ==3) {
                     myPatienten.Add("SMS an Krankenschwester: '" + myItem.Data.name + "' (kritisch)");
                 }
                 else if (myItem.Data.getStatus() == 4)
                 {
                     myPatienten.Add("SMS an Krankenschwester & Arzt: '" + myItem.Data.name + "' (sehr kritisch)");
                 }

             }  

             String tmp="";
             for (int i=0 ; i< myPatienten.Count;i++) {
                 tmp = tmp + (String) myPatienten[i] +"\n";

             }  

                 // Eingabe nicht valide
                 toolTip1.ToolTipTitle = "Zustand";
                 toolTip1.Show(tmp, statusStrip1);

             

         }


         private void btnMeasureData_Click(object sender, EventArgs e)
         {
             tmrDisibleButton.Tag = "1";
             tmrRefreshList.Enabled = false;

             PatientList.PLItem mySelectedPatient = (PatientList.PLItem) patientList1.myList[patientList1.getSelected()];
             frmPatientView tmp = new frmPatientView();

             tmp.myID = mySelectedPatient.Data.ID;
             tmp.Vorname = mySelectedPatient.Data.vorname;
             tmp.Name = mySelectedPatient.Data.name;

             tmp.ShowDialog();

             //Liste wieder aufhellen
             patientList1.MakeDark(false);
             tmrRefreshList.Enabled = true;
             tmrDisibleButton.Tag = "0";
         }

         private void btnEdit_Click(object sender, MouseEventArgs e)
         {
             tmrDisibleButton.Tag = "1";
             tmrRefreshList.Enabled = false;

             frmEditPatientName frmEdit = new frmEditPatientName();
             PatientList.PLItem tmp = (PatientList.PLItem)patientList1.myList[patientList1.getSelected()];

             frmEdit.fkPaID = tmp.Data.ID;
             frmEdit.vorname = tmp.Data.vorname;
             frmEdit.name = tmp.Data.name;

             frmEdit.ShowDialog();

             //Liste wieder aufhellen
             patientList1.MakeDark(false);
             tmrRefreshList.Enabled = true;
             tmrDisibleButton.Tag = "0";
         }

 



    }
}
